import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import MinMaxScaler
from utils.cacular_date import cacular_date, getEveryDay
from config.indexcode import currency_list, code_list


# 实现归一化
scaler = MinMaxScaler(feature_range=(0, 100))

class NeedForFeature:

    def __init__(self, currency, date_list):
        self.file_list = currency_list + code_list
        self.currency_df = self.get_df(currency, date_list, type="normal")
        self.df_code = dict()
        for code in self.file_list:
            self.df_code[code] = self.get_df(code, date_list)

    def change_time(self, timer):
        if " " in timer:
            timer = timer.split(" ")[0]
        return timer

    def get_df(self, filename, date_list, type="minmax"):
        file = "data/%s.csv" % filename.replace('/', '')
        df = pd.read_csv(file)
        df = df.set_index('open_time')
        if 'change' not in df.columns:
            df['change'] = (df['close'] - df['close'].shift()) / df['close'].shift() * 100
        # 选取固定的列进行规范化
        dfchange = df.loc[:, 'change']
        dfchange.index = df.index
        df = df.loc[:, ['open','high','low','close','volume']]
        for date_ in date_list:
            if date_ not in df.index:
                tmp = df.mode(axis=0, numeric_only=True)
                tmp['open_time'] = date_
                tmp = pd.DataFrame(tmp.to_dict(), index=[0]).set_index('open_time')
                df = pd.concat([df, tmp])
                df.sort_values("open_time", inplace=True)
        df = df[date_list[0]:date_list[-1]]
        dfchange = dfchange[date_list[0]:date_list[-1]]
        if type == "minmax":
            df_list = df.values
            df_index = df.index
            df_list = scaler.fit_transform(df_list)
            df = pd.DataFrame(df_list, index=df_index, columns=['open','high','low','close','volume'])
        df = pd.concat([df, dfchange], axis=1)
        df = df.fillna(0)
        df = df[~df.index.duplicated(keep='first')]
        return df

    def get_12_data(self, date_list):
        index_file_list = list()
        for code in self.file_list:
            df_ = self.df_code[code]
            dfs_ = df_[date_list[0]: date_list[-1]]

            # 这里的result_是单个文件的12天的特征信息，需要把几个指标文件组合到一起。
            index_file_list.extend(dfs_.values.tolist())

        return index_file_list


    def get_16_price(self, date_, date_5, df):
        date_high_price = df.loc[date_]['high']   # 当天的开盘价相当于前一天的收盘价
        date_5_low_price = df.loc[date_5]['low']  # 第5天的开盘价相当于第4天的收盘价
        print("当前的日期是%s, 当天的最高价是%s\n第五天的日期是%s, 第五天的最低价是%s," %
              (date_,date_high_price,date_5, date_5_low_price))
        profit = date_5_low_price - date_high_price
        profit_margin = profit/date_high_price
        if profit_margin > 0.012:
            return 1
        else:
            return 0


    def getXy(self, date_list):

        # date_list是begin_date 一直到昨天的日期的list
        index_list = list()
        target_list = list()

        n = 0
        for date_ in date_list:
            n += 1
            # 这个date_是模拟当前日期
            # 12 天的数据应该是之前的数据
            date_12_ = cacular_date(date_, -12)
            # 这里要添加限制逻辑
            if date_12_ not in date_list:
                print(date_, "第%s天跳过" % n)
                continue
            date_5 = cacular_date(date_, 5)
            if date_5 > date_list[-1]:
                print(date_, date_5, "第%s天超出边界" % n)
                break
            print(date_, "第%s天正在进行计算" % n)
            # 这里的index_data是12天的指标数据的特征 [[1,2,3,4,5], [2,2,3,4,5], ... , [12,2,3,4,5]]
            date12_list = getEveryDay(date_12_, cacular_date(date_, -1))
            index_data = self.get_12_data(date12_list)
            index_list.append(index_data)
            target = self.get_16_price(date_, date_5, self.currency_df)
            target_list.append(target)
        index_array = np.array(index_list)
        nsamples, nx, ny = index_array.shape
        X_array = index_array.reshape((nsamples, nx * ny))
        target_array = np.array(target_list)

        np.savetxt("data/X.csv", X_array, delimiter=",")
        np.savetxt("data/y.csv", target_array, delimiter=",", fmt='%d')
